// index.js
const { questionCategories } = require('../../utils/questions.js');

Page({
  data: {
    categories: questionCategories,
    currentTab: 0, // 默认显示第一个分类（后端）
    currentTopic: null, // 当前选中的专题
    currentCategoryName: '', // 当前分类名称
    currentTopicName: '', // 当前专题名称
    currentTopicQuestions: [], // 当前专题的题目列表
    searchValue: ''
  },
  
  onLoad() {
    // 页面加载时设置默认分类
    this.setData({
      currentTab: 0,
      currentTopic: null
    });
    this.updateCurrentData();
  },
  
  onTabChange(e) {
    const index = e.currentTarget.dataset.index;
    console.log('切换到分类:', index, this.data.categories[index].name);
    this.setData({ 
      currentTab: index,
      currentTopic: null // 切换分类时清空专题选择
    });
    this.updateCurrentData();
  },
  
  onTopicTap(e) {
    const topicId = e.currentTarget.dataset.topicId;
    const topic = this.data.categories[this.data.currentTab].topics.find(t => t.id === topicId);
    console.log('选择专题:', topicId, topic.name);
    this.setData({ 
      currentTopic: topicId 
    });
    this.updateCurrentData();
  },
  
  onBackToTopics() {
    this.setData({ 
      currentTopic: null 
    });
    this.updateCurrentData();
  },
  
  onSearchInput(e) {
    this.setData({ searchValue: e.detail.value });
  },
  
  onQuestionTap(e) {
    const { categoryId, topicId, questionId } = e.currentTarget.dataset;
    console.log('点击题目:', categoryId, topicId, questionId);
    wx.navigateTo({
      url: `/pages/detail/detail?categoryId=${categoryId}&topicId=${topicId}&questionId=${questionId}`
    });
  },
  
  // 更新当前显示的数据
  updateCurrentData() {
    const currentCategory = this.data.categories[this.data.currentTab];
    let currentTopicName = '';
    let currentTopicQuestions = [];
    
    if (this.data.currentTopic) {
      const topic = currentCategory.topics.find(t => t.id === this.data.currentTopic);
      if (topic) {
        currentTopicName = topic.name;
        currentTopicQuestions = topic.questions;
      }
    }
    
    this.setData({
      currentCategoryName: currentCategory.name,
      currentTopicName: currentTopicName,
      currentTopicQuestions: currentTopicQuestions
    });
  }
});
